# Copyright (c) 2019 Adam Michael
# Copyright (c) 2021 homuler
#
# Use of this source code is governed by an MIT-style
# license that can be found in the LICENSE file or at
#  https://opensource.org/licenses/MIT.

# Based on https://github.com/aj-michael/aar_with_jni/blob/b284343108b1e4cbfdbbf155bbcfa0b06e878f79/aar_with_jni.bzl

"""AAR Generator

Macro to generate AAR, including libmediapipe_jni.so
"""

load("@build_bazel_rules_android//android:rules.bzl", "android_binary", "android_library")

def mediapipe_aar(name, package = "com.github.homuler.mediapipe", srcs = [], deps = [], jni_deps = [], assets = [], assets_dir = "", target_sdk_version = 27, min_sdk_version = 21):
    """Generate MediaPipeUnityPlugin AAR.

    Args:
      package: package name
      name: the name of the AAR
      srcs: java source files
      deps: aar's dependencies (e.g. .so files)
      jni_deps: additional dependencies that will be linked to libmediapipe_jni.so
      assets: additional assets to be included into the archive.
      assets_dir: path where the assets will the packaged
      target_sdk_version: AAR's target SDK version
      min_sdk_version: AAR's min SDK version
    """
    native.cc_binary(
        name = "libmediapipe_jni.so",
        linkshared = 1,
        linkstatic = 1,
        deps = jni_deps,
    )

    native.cc_library(
        name = name + "_mediapipe_jni_lib",
        srcs = [":libmediapipe_jni.so"],
        alwayslink = 1,
    )

    native.genrule(
        name = name + "_aar_manifest_generator",
        outs = ["AndroidManifest.xml"],
        cmd = """
cat > $(OUTS) <<EOF
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="{}">
    <uses-sdk
        android:minSdkVersion="{}"
        android:targetSdkVersion="{}" />
    <application />
</manifest>
EOF
""".format(package, min_sdk_version, target_sdk_version),
    )

    android_library(
        name = name + "_android_lib",
        srcs = srcs,
        manifest = "AndroidManifest.xml",
        deps = [
            ":" + name + "_mediapipe_jni_lib",
        ] + deps,
        assets = assets,
        assets_dir = assets_dir,
    )

    _aar_with_jni(name, name + "_android_lib")

def _aar_with_jni(name, android_library):
    # Generate dummy AndroidManifest.xml for dummy apk usage
    # (dummy apk is generated by <name>_dummy_app target below)
    native.genrule(
        name = name + "_binary_manifest_generator",
        outs = [name + "_generated_AndroidManifest.xml"],
        cmd = """
cat > $(OUTS) <<EOF
<manifest
  xmlns:android="http://schemas.android.com/apk/res/android"
  package="dummy.package.for.so">
  <uses-sdk android:minSdkVersion="21"/>
</manifest>
EOF
""",
    )

    # Generate dummy apk including .so files.
    # We extract out .so files and throw away the apk.
    android_binary(
        name = name + "_dummy_app",
        manifest = name + "_generated_AndroidManifest.xml",
        custom_package = "dummy.package.for.so",
        deps = [android_library],
    )

    native.genrule(
        name = name,
        srcs = [android_library + ".aar", name + "_dummy_app_unsigned.apk"],
        outs = [name + ".aar"],
        tags = ["manual"],
        cmd = """
cp $(location {}.aar) $(location :{}.aar)
chmod +w $(location :{}.aar)
origdir=$$PWD
cd $$(mktemp -d)
unzip $$origdir/$(location :{}_dummy_app_unsigned.apk) "lib/**"
cp -r lib jni
zip -r $$origdir/$(location :{}.aar) jni/*/*.so
""".format(android_library, name, name, name, name),
    )
